package com.zenithmind.document.pojo.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import jakarta.validation.constraints.DecimalMax;
import jakarta.validation.constraints.DecimalMin;
import jakarta.validation.constraints.Size;

/**
 * 文档评分更新DTO
 * 遵循单一职责原则：专注于评分更新数据传输
 * 遵循开闭原则：支持字段的扩展
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Data
@Schema(description = "文档评分更新DTO")
public class DocumentRatingUpdateDTO {

    @Schema(description = "评分", example = "4.5", minimum = "1", maximum = "5")
    @DecimalMin(value = "1.0", message = "评分不能小于1.0")
    @DecimalMax(value = "5.0", message = "评分不能大于5.0")
    private Double rating;

    @Schema(description = "评论内容", example = "更新后的评论内容")
    @Size(max = 2000, message = "评论内容不能超过2000字符")
    private String comment;

    @Schema(description = "评分维度", example = "[{\"dimension\": \"内容质量\", \"score\": 5}, {\"dimension\": \"易读性\", \"score\": 4}]")
    private String ratingDimensions;

    @Schema(description = "评分标签", example = "有用,详细,清晰,更新")
    private String ratingTags;

    @Schema(description = "评分类型", example = "EXPERT", allowableValues = {"GENERAL", "EXPERT", "PEER_REVIEW", "AUTOMATED"})
    private String ratingType;

    @Schema(description = "是否匿名", example = "false")
    private Boolean isAnonymous;

    @Schema(description = "推荐给他人", example = "true")
    private Boolean recommendToOthers;

    @Schema(description = "推荐理由", example = "更新后的推荐理由")
    private String recommendReason;

    @Schema(description = "使用场景", example = "项目开发参考")
    private String usageScenario;

    @Schema(description = "阅读时长（分钟）", example = "45")
    private Integer readingDuration;

    @Schema(description = "文档版本", example = "v1.3")
    private String documentVersion;

    @Schema(description = "评分权重", example = "1.2")
    @DecimalMin(value = "0.1", message = "评分权重不能小于0.1")
    @DecimalMax(value = "2.0", message = "评分权重不能大于2.0")
    private Double ratingWeight;

    @Schema(description = "评分置信度", example = "0.9")
    @DecimalMin(value = "0.0", message = "置信度不能小于0.0")
    @DecimalMax(value = "1.0", message = "置信度不能大于1.0")
    private Double confidence;

    @Schema(description = "情感倾向", example = "POSITIVE", allowableValues = {"POSITIVE", "NEUTRAL", "NEGATIVE"})
    private String sentiment;

    @Schema(description = "关键词", example = "质量,内容,实用,更新")
    private String keywords;

    @Schema(description = "改进建议", example = "建议增加更多图表说明")
    private String improvementSuggestions;

    @Schema(description = "相关文档推荐", example = "doc789,doc101,doc202")
    private String relatedDocuments;

    @Schema(description = "评分上下文", example = "{\"project\": \"ProjectA\", \"team\": \"TeamB\", \"phase\": \"review\"}")
    private String ratingContext;

    @Schema(description = "扩展属性", example = "{\"category\": \"技术文档\", \"difficulty\": \"高级\"}")
    private String extendedProperties;

    @Schema(description = "备注", example = "评分更新备注")
    private String remarks;

    @Schema(description = "更新原因", example = "重新阅读后调整评分")
    private String updateReason;

    @Schema(description = "审核状态", example = "APPROVED", allowableValues = {"PENDING", "APPROVED", "REJECTED"})
    private String reviewStatus;

    @Schema(description = "审核意见", example = "评分更新合理")
    private String reviewComment;

    @Schema(description = "是否置顶", example = "false")
    private Boolean isPinned;

    @Schema(description = "是否公开", example = "true")
    private Boolean isPublic;

    @Schema(description = "状态", example = "ACTIVE", allowableValues = {"ACTIVE", "INACTIVE", "HIDDEN", "DELETED"})
    private String status;

    /**
     * 验证更新数据
     */
    public boolean isValid() {
        // 验证评分范围
        if (rating != null && (rating < 1.0 || rating > 5.0)) return false;
        
        // 验证评论长度
        if (comment != null && comment.length() > 2000) return false;
        
        // 验证权重范围
        if (ratingWeight != null && (ratingWeight < 0.1 || ratingWeight > 2.0)) return false;
        
        // 验证置信度范围
        if (confidence != null && (confidence < 0.0 || confidence > 1.0)) return false;
        
        // 验证阅读时长
        if (readingDuration != null && readingDuration < 0) return false;
        
        return true;
    }

    /**
     * 是否有评分更新
     */
    public boolean hasRatingUpdate() {
        return rating != null;
    }

    /**
     * 是否有评论更新
     */
    public boolean hasCommentUpdate() {
        return comment != null;
    }

    /**
     * 是否有标签更新
     */
    public boolean hasTagsUpdate() {
        return ratingTags != null;
    }

    /**
     * 是否有维度更新
     */
    public boolean hasDimensionsUpdate() {
        return ratingDimensions != null;
    }

    /**
     * 是否有推荐状态更新
     */
    public boolean hasRecommendationUpdate() {
        return recommendToOthers != null || recommendReason != null;
    }

    /**
     * 是否为评分提升
     */
    public boolean isRatingIncrease(Double currentRating) {
        return rating != null && currentRating != null && rating > currentRating;
    }

    /**
     * 是否为评分降低
     */
    public boolean isRatingDecrease(Double currentRating) {
        return rating != null && currentRating != null && rating < currentRating;
    }

    /**
     * 是否为高分评价
     */
    public boolean isHighRating() {
        return rating != null && rating >= 4.0;
    }

    /**
     * 是否为低分评价
     */
    public boolean isLowRating() {
        return rating != null && rating <= 2.0;
    }

    /**
     * 获取评分变化幅度
     */
    public double getRatingChange(Double currentRating) {
        if (rating == null || currentRating == null) return 0.0;
        return rating - currentRating;
    }

    /**
     * 获取评分标签列表
     */
    public String[] getRatingTagArray() {
        if (ratingTags == null || ratingTags.trim().isEmpty()) {
            return new String[0];
        }
        return ratingTags.split(",");
    }

    /**
     * 获取关键词列表
     */
    public String[] getKeywordArray() {
        if (keywords == null || keywords.trim().isEmpty()) {
            return new String[0];
        }
        return keywords.split(",");
    }

    /**
     * 获取相关文档列表
     */
    public String[] getRelatedDocumentArray() {
        if (relatedDocuments == null || relatedDocuments.trim().isEmpty()) {
            return new String[0];
        }
        return relatedDocuments.split(",");
    }

    /**
     * 获取更新摘要
     */
    public String getUpdateSummary() {
        StringBuilder summary = new StringBuilder();
        
        if (hasRatingUpdate()) {
            summary.append("评分: ").append(rating).append("; ");
        }
        
        if (hasCommentUpdate()) {
            summary.append("评论已更新; ");
        }
        
        if (hasTagsUpdate()) {
            summary.append("标签已更新; ");
        }
        
        if (hasDimensionsUpdate()) {
            summary.append("维度评分已更新; ");
        }
        
        if (hasRecommendationUpdate()) {
            summary.append("推荐状态已更新; ");
        }
        
        if (ratingType != null) {
            summary.append("评分类型: ").append(ratingType).append("; ");
        }
        
        if (status != null) {
            summary.append("状态: ").append(status).append("; ");
        }
        
        return summary.length() > 0 ? summary.toString() : "无更新";
    }

    /**
     * 创建评分调整更新
     */
    public static DocumentRatingUpdateDTO createRatingAdjustment(Double newRating, String reason) {
        DocumentRatingUpdateDTO dto = new DocumentRatingUpdateDTO();
        dto.setRating(newRating);
        dto.setUpdateReason(reason);
        dto.setConfidence(0.8);
        return dto;
    }

    /**
     * 创建评论更新
     */
    public static DocumentRatingUpdateDTO createCommentUpdate(String newComment, String reason) {
        DocumentRatingUpdateDTO dto = new DocumentRatingUpdateDTO();
        dto.setComment(newComment);
        dto.setUpdateReason(reason);
        return dto;
    }

    /**
     * 创建推荐状态更新
     */
    public static DocumentRatingUpdateDTO createRecommendationUpdate(Boolean recommend, String reason) {
        DocumentRatingUpdateDTO dto = new DocumentRatingUpdateDTO();
        dto.setRecommendToOthers(recommend);
        dto.setRecommendReason(reason);
        dto.setUpdateReason("推荐状态调整");
        return dto;
    }

    /**
     * 创建状态更新
     */
    public static DocumentRatingUpdateDTO createStatusUpdate(String newStatus, String reason) {
        DocumentRatingUpdateDTO dto = new DocumentRatingUpdateDTO();
        dto.setStatus(newStatus);
        dto.setUpdateReason(reason);
        return dto;
    }

    /**
     * 创建审核更新
     */
    public static DocumentRatingUpdateDTO createReviewUpdate(String reviewStatus, String reviewComment) {
        DocumentRatingUpdateDTO dto = new DocumentRatingUpdateDTO();
        dto.setReviewStatus(reviewStatus);
        dto.setReviewComment(reviewComment);
        dto.setUpdateReason("审核处理");
        return dto;
    }

    /**
     * 计算更新质量分数
     */
    public double calculateUpdateQualityScore() {
        double score = 0.0;
        
        // 评分更新权重 30%
        if (hasRatingUpdate()) {
            score += 0.3;
        }
        
        // 评论更新权重 40%
        if (hasCommentUpdate() && comment != null && comment.length() > 10) {
            score += 0.4;
        }
        
        // 标签更新权重 15%
        if (hasTagsUpdate()) {
            score += 0.15;
        }
        
        // 维度更新权重 10%
        if (hasDimensionsUpdate()) {
            score += 0.1;
        }
        
        // 更新原因权重 5%
        if (updateReason != null && !updateReason.trim().isEmpty()) {
            score += 0.05;
        }
        
        return Math.min(score, 1.0);
    }

    /**
     * 是否为重要更新
     */
    public boolean isSignificantUpdate() {
        return hasRatingUpdate() || hasCommentUpdate() || hasDimensionsUpdate();
    }

    /**
     * 是否需要审核
     */
    public boolean needsReview() {
        return hasRatingUpdate() && (isHighRating() || isLowRating());
    }
}
